package com.dd.utils.file

import android.content.Context
import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.tencent.mmkv.MMKV
import java.io.File
import java.util.Collections

class DataCacheMMKVManager {
    private val CACHE_DATA = "CACHE_DATA"
    private val USER_LAST_DATE = "USER_LAST_DATE"
    private val mmkv: MMKV = MMKV.mmkvWithID(CACHE_DATA)

    fun setUserLastDate(map: Map<*, *>) {
        try {
            mmkv.encode(USER_LAST_DATE, Gson().toJson(map))
        } catch (_: Exception) {
        }
    }

    fun getUserLastDate(context: Context): Map<File, Long>? {
        mmkv.decodeString(USER_LAST_DATE)?.let {
            val jsonMap: String = it
            val map = Collections.synchronizedMap(HashMap<File, Long>())
            if (TextUtils.isEmpty(jsonMap)) {
                return map
            }
            val jsonObject: JsonObject = Gson().fromJson(jsonMap, JsonObject::class.java)
            val entrySet: Set<Map.Entry<String, JsonElement>> = jsonObject.entrySet()

            for (entry: Map.Entry<String, JsonElement?> in entrySet) {
                val value: Long = Gson().fromJson(entry.value, Long::class.java)
                val file: File = FileUtil.newFile(DATA_CACHE, entry.key, context)
                map[file] = value
            }
            map
        }
        return null
    }
}